home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / pyshared / atom / service.py < prev    next >
Encoding:
Python Source  |  2010-04-02  |  28.2 KB  |  740 lines

  1. #
  2. # Copyright (C) 2006, 2007, 2008 Google Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. #      http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15.  
  16.  
  17. """AtomService provides CRUD ops. in line with the Atom Publishing Protocol.
  18.  
  19.   AtomService: Encapsulates the ability to perform insert, update and delete
  20.                operations with the Atom Publishing Protocol on which GData is
  21.                based. An instance can perform query, insertion, deletion, and
  22.                update.
  23.  
  24.   HttpRequest: Function that performs a GET, POST, PUT, or DELETE HTTP request
  25.        to the specified end point. An AtomService object or a subclass can be
  26.        used to specify information about the request.
  27. """
  28.  
  29. __author__ = 'api.jscudder (Jeff Scudder)'
  30.  
  31.  
  32. import atom.http_interface
  33. import atom.url
  34. import atom.http
  35. import atom.token_store
  36.  
  37. import os
  38. import httplib
  39. import urllib
  40. import re
  41. import base64
  42. import socket
  43. import warnings
  44. try:
  45.   from xml.etree import cElementTree as ElementTree
  46. except ImportError:
  47.   try:
  48.     import cElementTree as ElementTree
  49.   except ImportError:
  50.     try:
  51.       from xml.etree import ElementTree
  52.     except ImportError:
  53.       from elementtree import ElementTree
  54. import atom
  55.  
  56.  
  57. class AtomService(object):
  58.   """Performs Atom Publishing Protocol CRUD operations.
  59.   
  60.   The AtomService contains methods to perform HTTP CRUD operations. 
  61.   """
  62.  
  63.   # Default values for members
  64.   port = 80
  65.   ssl = False
  66.   # Set the current_token to force the AtomService to use this token
  67.   # instead of searching for an appropriate token in the token_store.
  68.   current_token = None
  69.   auto_store_tokens = True
  70.   auto_set_current_token = True
  71.  
  72.   def _get_override_token(self):
  73.     return self.current_token
  74.  
  75.   def _set_override_token(self, token):
  76.     self.current_token = token
  77.  
  78.   override_token = property(_get_override_token, _set_override_token)
  79.  
  80.   #@atom.v1_deprecated('Please use atom.client.AtomPubClient instead.')
  81.   def __init__(self, server=None, additional_headers=None, 
  82.       application_name='', http_client=None, token_store=None):
  83.     """Creates a new AtomService client.
  84.     
  85.     Args:
  86.       server: string (optional) The start of a URL for the server
  87.               to which all operations should be directed. Example: 
  88.               'www.google.com'
  89.       additional_headers: dict (optional) Any additional HTTP headers which
  90.                           should be included with CRUD operations.
  91.       http_client: An object responsible for making HTTP requests using a
  92.                    request method. If none is provided, a new instance of
  93.                    atom.http.ProxiedHttpClient will be used.
  94.       token_store: Keeps a collection of authorization tokens which can be
  95.                    applied to requests for a specific URLs. Critical methods are
  96.                    find_token based on a URL (atom.url.Url or a string), add_token,
  97.                    and remove_token.
  98.     """
  99.     self.http_client = http_client or atom.http.ProxiedHttpClient()
  100.     self.token_store = token_store or atom.token_store.TokenStore()
  101.     self.server = server
  102.     self.additional_headers = additional_headers or {}
  103.     self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % (
  104.         application_name,)
  105.     # If debug is True, the HTTPConnection will display debug information
  106.     self._set_debug(False)
  107.  
  108.   __init__ = atom.v1_deprecated(
  109.       'Please use atom.client.AtomPubClient instead.')(
  110.           __init__)
  111.  
  112.   def _get_debug(self):
  113.     return self.http_client.debug
  114.  
  115.   def _set_debug(self, value):
  116.     self.http_client.debug = value
  117.  
  118.   debug = property(_get_debug, _set_debug, 
  119.       doc='If True, HTTP debug information is printed.')
  120.  
  121.   def use_basic_auth(self, username, password, scopes=None):
  122.     if username is not None and password is not None:
  123.       if scopes is None:
  124.         scopes = [atom.token_store.SCOPE_ALL]
  125.       base_64_string = base64.encodestring('%s:%s' % (username, password))
  126.       token = BasicAuthToken('Basic %s' % base_64_string.strip(), 
  127.           scopes=[atom.token_store.SCOPE_ALL])
  128.       if self.auto_set_current_token:
  129.         self.current_token = token
  130.       if self.auto_store_tokens:
  131.         return self.token_store.add_token(token)
  132.       return True
  133.     return False
  134.  
  135.   def UseBasicAuth(self, username, password, for_proxy=False):
  136.     """Sets an Authenticaiton: Basic HTTP header containing plaintext.
  137.  
  138.     Deprecated, use use_basic_auth instead.
  139.     
  140.     The username and password are base64 encoded and added to an HTTP header
  141.     which will be included in each request. Note that your username and 
  142.     password are sent in plaintext.
  143.  
  144.     Args:
  145.       username: str
  146.       password: str
  147.     """
  148.     self.use_basic_auth(username, password)
  149.  
  150.   #@atom.v1_deprecated('Please use atom.client.AtomPubClient for requests.')
  151.   def request(self, operation, url, data=None, headers=None, 
  152.       url_params=None):
  153.     if isinstance(url, (str, unicode)):
  154.       if url.startswith('http:') and self.ssl:
  155.         # Force all requests to be https if self.ssl is True.
  156.         url = atom.url.parse_url('https:' + url[5:])
  157.       elif not url.startswith('http') and self.ssl: 
  158.         url = atom.url.parse_url('https://%s%s' % (self.server, url))
  159.       elif not url.startswith('http'):
  160.         url = atom.url.parse_url('http://%s%s' % (self.server, url))
  161.       else:
  162.         url = atom.url.parse_url(url)
  163.  
  164.     if url_params:
  165.       for name, value in url_params.iteritems():
  166.         url.params[name] = value
  167.  
  168.     all_headers = self.additional_headers.copy()
  169.     if headers:
  170.       all_headers.update(headers)
  171.  
  172.     # If the list of headers does not include a Content-Length, attempt to
  173.     # calculate it based on the data object.
  174.     if data and 'Content-Length' not in all_headers:
  175.       content_length = CalculateDataLength(data)
  176.       if content_length:
  177.         all_headers['Content-Length'] = str(content_length)
  178.  
  179.     # Find an Authorization token for this URL if one is available.
  180.     if self.override_token:
  181.       auth_token = self.override_token
  182.     else:
  183.       auth_token = self.token_store.find_token(url)
  184.     return auth_token.perform_request(self.http_client, operation, url, 
  185.         data=data, headers=all_headers)
  186.  
  187.   request = atom.v1_deprecated(
  188.       'Please use atom.client.AtomPubClient for requests.')(
  189.           request)
  190.  
  191.   # CRUD operations
  192.   def Get(self, uri, extra_headers=None, url_params=None, escape_params=True):
  193.     """Query the APP server with the given URI
  194.  
  195.     The uri is the portion of the URI after the server value 
  196.     (server example: 'www.google.com').
  197.  
  198.     Example use:
  199.     To perform a query against Google Base, set the server to 
  200.     'base.google.com' and set the uri to '/base/feeds/...', where ... is 
  201.     your query. For example, to find snippets for all digital cameras uri 
  202.     should be set to: '/base/feeds/snippets?bq=digital+camera'
  203.  
  204.     Args:
  205.       uri: string The query in the form of a URI. Example:
  206.            '/base/feeds/snippets?bq=digital+camera'.
  207.       extra_headers: dicty (optional) Extra HTTP headers to be included
  208.                      in the GET request. These headers are in addition to 
  209.                      those stored in the client's additional_headers property.
  210.                      The client automatically sets the Content-Type and 
  211.                      Authorization headers.
  212.       url_params: dict (optional) Additional URL parameters to be included
  213.                   in the query. These are translated into query arguments
  214.                   in the form '&dict_key=value&...'.
  215.                   Example: {'max-results': '250'} becomes &max-results=250
  216.       escape_params: boolean (optional) If false, the calling code has already
  217.                      ensured that the query will form a valid URL (all
  218.                      reserved characters have been escaped). If true, this
  219.                      method will escape the query and any URL parameters
  220.                      provided.
  221.  
  222.     Returns:
  223.       httplib.HTTPResponse The server's response to the GET request.
  224.     """
  225.     return self.request('GET', uri, data=None, headers=extra_headers, 
  226.                         url_params=url_params)
  227.  
  228.   def Post(self, data, uri, extra_headers=None, url_params=None, 
  229.            escape_params=True, content_type='application/atom+xml'):
  230.     """Insert data into an APP server at the given URI.
  231.  
  232.     Args:
  233.       data: string, ElementTree._Element, or something with a __str__ method 
  234.             The XML to be sent to the uri. 
  235.       uri: string The location (feed) to which the data should be inserted. 
  236.            Example: '/base/feeds/items'. 
  237.       extra_headers: dict (optional) HTTP headers which are to be included. 
  238.                      The client automatically sets the Content-Type,
  239.                      Authorization, and Content-Length headers.
  240.       url_params: dict (optional) Additional URL parameters to be included
  241.                   in the URI. These are translated into query arguments
  242.                   in the form '&dict_key=value&...'.
  243.                   Example: {'max-results': '250'} becomes &max-results=250
  244.       escape_params: boolean (optional) If false, the calling code has already
  245.                      ensured that the query will form a valid URL (all
  246.                      reserved characters have been escaped). If true, this
  247.                      method will escape the query and any URL parameters
  248.                      provided.
  249.  
  250.     Returns:
  251.       httplib.HTTPResponse Server's response to the POST request.
  252.     """
  253.     if extra_headers is None:
  254.       extra_headers = {}
  255.     if content_type:
  256.       extra_headers['Content-Type'] = content_type
  257.     return self.request('POST', uri, data=data, headers=extra_headers, 
  258.                         url_params=url_params)
  259.  
  260.   def Put(self, data, uri, extra_headers=None, url_params=None, 
  261.            escape_params=True, content_type='application/atom+xml'):
  262.     """Updates an entry at the given URI.
  263.      
  264.     Args:
  265.       data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The 
  266.             XML containing the updated data.
  267.       uri: string A URI indicating entry to which the update will be applied.
  268.            Example: '/base/feeds/items/ITEM-ID'
  269.       extra_headers: dict (optional) HTTP headers which are to be included.
  270.                      The client automatically sets the Content-Type,
  271.                      Authorization, and Content-Length headers.
  272.       url_params: dict (optional) Additional URL parameters to be included
  273.                   in the URI. These are translated into query arguments
  274.                   in the form '&dict_key=value&...'.
  275.                   Example: {'max-results': '250'} becomes &max-results=250
  276.       escape_params: boolean (optional) If false, the calling code has already
  277.                      ensured that the query will form a valid URL (all
  278.                      reserved characters have been escaped). If true, this
  279.                      method will escape the query and any URL parameters
  280.                      provided.
  281.   
  282.     Returns:
  283.       httplib.HTTPResponse Server's response to the PUT request.
  284.     """
  285.     if extra_headers is None:
  286.       extra_headers = {}
  287.     if content_type:
  288.       extra_headers['Content-Type'] = content_type
  289.     return self.request('PUT', uri, data=data, headers=extra_headers, 
  290.                         url_params=url_params)
  291.  
  292.   def Delete(self, uri, extra_headers=None, url_params=None, 
  293.              escape_params=True):
  294.     """Deletes the entry at the given URI.
  295.  
  296.     Args:
  297.       uri: string The URI of the entry to be deleted. Example: 
  298.            '/base/feeds/items/ITEM-ID'
  299.       extra_headers: dict (optional) HTTP headers which are to be included.
  300.                      The client automatically sets the Content-Type and
  301.                      Authorization headers.
  302.       url_params: dict (optional) Additional URL parameters to be included
  303.                   in the URI. These are translated into query arguments
  304.                   in the form '&dict_key=value&...'.
  305.                   Example: {'max-results': '250'} becomes &max-results=250
  306.       escape_params: boolean (optional) If false, the calling code has already
  307.                      ensured that the query will form a valid URL (all
  308.                      reserved characters have been escaped). If true, this
  309.                      method will escape the query and any URL parameters
  310.                      provided.
  311.  
  312.     Returns:
  313.       httplib.HTTPResponse Server's response to the DELETE request.
  314.     """
  315.     return self.request('DELETE', uri, data=None, headers=extra_headers, 
  316.                         url_params=url_params)
  317.  
  318.  
  319. class BasicAuthToken(atom.http_interface.GenericToken):
  320.   def __init__(self, auth_header, scopes=None):
  321.     """Creates a token used to add Basic Auth headers to HTTP requests.
  322.  
  323.     Args:
  324.       auth_header: str The value for the Authorization header.
  325.       scopes: list of str or atom.url.Url specifying the beginnings of URLs
  326.           for which this token can be used. For example, if scopes contains
  327.           'http://example.com/foo', then this token can be used for a request to
  328.           'http://example.com/foo/bar' but it cannot be used for a request to
  329.           'http://example.com/baz'
  330.     """
  331.     self.auth_header = auth_header
  332.     self.scopes = scopes or []
  333.  
  334.   def perform_request(self, http_client, operation, url, data=None,
  335.                       headers=None):
  336.     """Sets the Authorization header to the basic auth string."""
  337.     if headers is None:
  338.       headers = {'Authorization':self.auth_header}
  339.     else:
  340.       headers['Authorization'] = self.auth_header
  341.     return http_client.request(operation, url, data=data, headers=headers)
  342.  
  343.   def __str__(self):
  344.     return self.auth_header
  345.  
  346.   def valid_for_scope(self, url):
  347.     """Tells the caller if the token authorizes access to the desired URL.
  348.     """
  349.     if isinstance(url, (str, unicode)):
  350.       url = atom.url.parse_url(url)
  351.     for scope in self.scopes:
  352.       if scope == atom.token_store.SCOPE_ALL:
  353.         return True
  354.       if isinstance(scope, (str, unicode)):
  355.         scope = atom.url.parse_url(scope)
  356.       if scope == url:
  357.         return True
  358.       # Check the host and the path, but ignore the port and protocol.
  359.       elif scope.host == url.host and not scope.path:
  360.         return True
  361.       elif scope.host == url.host and scope.path and not url.path:
  362.         continue
  363.       elif scope.host == url.host and url.path.startswith(scope.path):
  364.         return True
  365.     return False
  366.  
  367.  
  368. def PrepareConnection(service, full_uri):
  369.   """Opens a connection to the server based on the full URI.
  370.  
  371.   This method is deprecated, instead use atom.http.HttpClient.request.
  372.  
  373.   Examines the target URI and the proxy settings, which are set as
  374.   environment variables, to open a connection with the server. This
  375.   connection is used to make an HTTP request.
  376.  
  377.   Args:
  378.     service: atom.AtomService or a subclass. It must have a server string which
  379.       represents the server host to which the request should be made. It may also
  380.       have a dictionary of additional_headers to send in the HTTP request.
  381.     full_uri: str Which is the target relative (lacks protocol and host) or
  382.     absolute URL to be opened. Example:
  383.     'https://www.google.com/accounts/ClientLogin' or
  384.     'base/feeds/snippets' where the server is set to www.google.com.
  385.  
  386.   Returns:
  387.     A tuple containing the httplib.HTTPConnection and the full_uri for the
  388.     request.
  389.   """
  390.   deprecation('calling deprecated function PrepareConnection')
  391.   (server, port, ssl, partial_uri) = ProcessUrl(service, full_uri)
  392.   if ssl:
  393.     # destination is https
  394.     proxy = os.environ.get('https_proxy')
  395.     if proxy:
  396.       (p_server, p_port, p_ssl, p_uri) = ProcessUrl(service, proxy, True)
  397.       proxy_username = os.environ.get('proxy-username')
  398.       if not proxy_username:
  399.         proxy_username = os.environ.get('proxy_username')
  400.       proxy_password = os.environ.get('proxy-password')
  401.       if not proxy_password:
  402.         proxy_password = os.environ.get('proxy_password')
  403.       if proxy_username:
  404.         user_auth = base64.encodestring('%s:%s' % (proxy_username,
  405.                                                    proxy_password))
  406.         proxy_authorization = ('Proxy-authorization: Basic %s\r\n' % (
  407.             user_auth.strip()))
  408.       else:
  409.         proxy_authorization = ''
  410.       proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (server, port)
  411.       user_agent = 'User-Agent: %s\r\n' % (
  412.           service.additional_headers['User-Agent'])
  413.       proxy_pieces = (proxy_connect + proxy_authorization + user_agent
  414.                        + '\r\n')
  415.  
  416.       #now connect, very simple recv and error checking
  417.       p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  418.       p_sock.connect((p_server,p_port))
  419.       p_sock.sendall(proxy_pieces)
  420.       response = ''
  421.  
  422.       # Wait for the full response.
  423.       while response.find("\r\n\r\n") == -1:
  424.         response += p_sock.recv(8192)
  425.        
  426.       p_status=response.split()[1]
  427.       if p_status!=str(200):
  428.         raise 'Error status=',str(p_status)
  429.  
  430.       # Trivial setup for ssl socket.
  431.       ssl = socket.ssl(p_sock, None, None)
  432.       fake_sock = httplib.FakeSocket(p_sock, ssl)
  433.  
  434.       # Initalize httplib and replace with the proxy socket.
  435.       connection = httplib.HTTPConnection(server)
  436.       connection.sock=fake_sock
  437.       full_uri = partial_uri
  438.  
  439.     else:
  440.       connection = httplib.HTTPSConnection(server, port)
  441.       full_uri = partial_uri
  442.  
  443.   else:
  444.     # destination is http
  445.     proxy = os.environ.get('http_proxy')
  446.     if proxy:
  447.       (p_server, p_port, p_ssl, p_uri) = ProcessUrl(service.server, proxy, True)
  448.       proxy_username = os.environ.get('proxy-username')
  449.       if not proxy_username:
  450.         proxy_username = os.environ.get('proxy_username')
  451.       proxy_password = os.environ.get('proxy-password')
  452.       if not proxy_password:
  453.         proxy_password = os.environ.get('proxy_password')
  454.       if proxy_username:
  455.         UseBasicAuth(service, proxy_username, proxy_password, True)
  456.       connection = httplib.HTTPConnection(p_server, p_port)
  457.       if not full_uri.startswith("http://"):
  458.         if full_uri.startswith("/"):
  459.           full_uri = "http://%s%s" % (service.server, full_uri)
  460.         else:
  461.           full_uri = "http://%s/%s" % (service.server, full_uri)
  462.     else:
  463.       connection = httplib.HTTPConnection(server, port)
  464.       full_uri = partial_uri
  465.  
  466.   return (connection, full_uri)
  467.  
  468.  
  469. def UseBasicAuth(service, username, password, for_proxy=False):
  470.   """Sets an Authenticaiton: Basic HTTP header containing plaintext.
  471.  
  472.   Deprecated, use AtomService.use_basic_auth insread.
  473.   
  474.   The username and password are base64 encoded and added to an HTTP header
  475.   which will be included in each request. Note that your username and 
  476.   password are sent in plaintext. The auth header is added to the 
  477.   additional_headers dictionary in the service object.
  478.  
  479.   Args:
  480.     service: atom.AtomService or a subclass which has an 
  481.         additional_headers dict as a member.
  482.     username: str
  483.     password: str
  484.   """
  485.   deprecation('calling deprecated function UseBasicAuth')
  486.   base_64_string = base64.encodestring('%s:%s' % (username, password))
  487.   base_64_string = base_64_string.strip()
  488.   if for_proxy:
  489.     header_name = 'Proxy-Authorization'
  490.   else:
  491.     header_name = 'Authorization'
  492.   service.additional_headers[header_name] = 'Basic %s' % (base_64_string,)
  493.  
  494.  
  495. def ProcessUrl(service, url, for_proxy=False):
  496.   """Processes a passed URL.  If the URL does not begin with https?, then
  497.   the default value for server is used
  498.  
  499.   This method is deprecated, use atom.url.parse_url instead.
  500.   """
  501.   if not isinstance(url, atom.url.Url):
  502.     url = atom.url.parse_url(url)
  503.  
  504.   server = url.host
  505.   ssl = False
  506.   port = 80
  507.  
  508.   if not server:
  509.     if hasattr(service, 'server'):
  510.       server = service.server
  511.     else:
  512.       server = service
  513.     if not url.protocol and hasattr(service, 'ssl'):
  514.       ssl = service.ssl
  515.     if hasattr(service, 'port'):
  516.       port = service.port
  517.   else:
  518.     if url.protocol == 'https':
  519.       ssl = True
  520.     elif url.protocol == 'http':
  521.       ssl = False
  522.     if url.port:
  523.       port = int(url.port)
  524.     elif port == 80 and ssl:
  525.       port = 443
  526.  
  527.   return (server, port, ssl, url.get_request_uri())
  528.  
  529. def DictionaryToParamList(url_parameters, escape_params=True):
  530.   """Convert a dictionary of URL arguments into a URL parameter string.
  531.  
  532.   This function is deprcated, use atom.url.Url instead.
  533.  
  534.   Args:
  535.     url_parameters: The dictionaty of key-value pairs which will be converted
  536.                     into URL parameters. For example,
  537.                     {'dry-run': 'true', 'foo': 'bar'}
  538.                     will become ['dry-run=true', 'foo=bar'].
  539.  
  540.   Returns:
  541.     A list which contains a string for each key-value pair. The strings are
  542.     ready to be incorporated into a URL by using '&'.join([] + parameter_list)
  543.   """
  544.   # Choose which function to use when modifying the query and parameters.
  545.   # Use quote_plus when escape_params is true.
  546.   transform_op = [str, urllib.quote_plus][bool(escape_params)]
  547.   # Create a list of tuples containing the escaped version of the
  548.   # parameter-value pairs.
  549.   parameter_tuples = [(transform_op(param), transform_op(value))
  550.                      for param, value in (url_parameters or {}).items()]
  551.   # Turn parameter-value tuples into a list of strings in the form
  552.   # 'PARAMETER=VALUE'.
  553.   return ['='.join(x) for x in parameter_tuples]
  554.  
  555.  
  556. def BuildUri(uri, url_params=None, escape_params=True):
  557.   """Converts a uri string and a collection of parameters into a URI.
  558.  
  559.   This function is deprcated, use atom.url.Url instead.
  560.  
  561.   Args:
  562.     uri: string
  563.     url_params: dict (optional)
  564.     escape_params: boolean (optional)
  565.     uri: string The start of the desired URI. This string can alrady contain
  566.          URL parameters. Examples: '/base/feeds/snippets', 
  567.          '/base/feeds/snippets?bq=digital+camera'
  568.     url_parameters: dict (optional) Additional URL parameters to be included
  569.                     in the query. These are translated into query arguments
  570.                     in the form '&dict_key=value&...'.
  571.                     Example: {'max-results': '250'} becomes &max-results=250
  572.     escape_params: boolean (optional) If false, the calling code has already
  573.                    ensured that the query will form a valid URL (all
  574.                    reserved characters have been escaped). If true, this
  575.                    method will escape the query and any URL parameters
  576.                    provided.
  577.  
  578.   Returns:
  579.     string The URI consisting of the escaped URL parameters appended to the
  580.     initial uri string.
  581.   """
  582.   # Prepare URL parameters for inclusion into the GET request.
  583.   parameter_list = DictionaryToParamList(url_params, escape_params)
  584.  
  585.   # Append the URL parameters to the URL.
  586.   if parameter_list:
  587.     if uri.find('?') != -1:
  588.       # If there are already URL parameters in the uri string, add the
  589.       # parameters after a new & character.
  590.       full_uri = '&'.join([uri] + parameter_list)
  591.     else:
  592.       # The uri string did not have any URL parameters (no ? character)
  593.       # so put a ? between the uri and URL parameters.
  594.       full_uri = '%s%s' % (uri, '?%s' % ('&'.join([] + parameter_list)))  
  595.   else:
  596.     full_uri = uri
  597.         
  598.   return full_uri
  599.  
  600.   
  601. def HttpRequest(service, operation, data, uri, extra_headers=None, 
  602.     url_params=None, escape_params=True, content_type='application/atom+xml'):
  603.   """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
  604.   
  605.   This method is deprecated, use atom.http.HttpClient.request instead.
  606.  
  607.   Usage example, perform and HTTP GET on http://www.google.com/:
  608.     import atom.service
  609.     client = atom.service.AtomService()
  610.     http_response = client.Get('http://www.google.com/')
  611.   or you could set the client.server to 'www.google.com' and use the 
  612.   following:
  613.     client.server = 'www.google.com'
  614.     http_response = client.Get('/')
  615.  
  616.   Args:
  617.     service: atom.AtomService object which contains some of the parameters 
  618.         needed to make the request. The following members are used to 
  619.         construct the HTTP call: server (str), additional_headers (dict), 
  620.         port (int), and ssl (bool).
  621.     operation: str The HTTP operation to be performed. This is usually one of
  622.         'GET', 'POST', 'PUT', or 'DELETE'
  623.     data: ElementTree, filestream, list of parts, or other object which can be 
  624.         converted to a string. 
  625.         Should be set to None when performing a GET or PUT.
  626.         If data is a file-like object which can be read, this method will read
  627.         a chunk of 100K bytes at a time and send them. 
  628.         If the data is a list of parts to be sent, each part will be evaluated
  629.         and sent.
  630.     uri: The beginning of the URL to which the request should be sent. 
  631.         Examples: '/', '/base/feeds/snippets', 
  632.         '/m8/feeds/contacts/default/base'
  633.     extra_headers: dict of strings. HTTP headers which should be sent
  634.         in the request. These headers are in addition to those stored in 
  635.         service.additional_headers.
  636.     url_params: dict of strings. Key value pairs to be added to the URL as
  637.         URL parameters. For example {'foo':'bar', 'test':'param'} will 
  638.         become ?foo=bar&test=param.
  639.     escape_params: bool default True. If true, the keys and values in 
  640.         url_params will be URL escaped when the form is constructed 
  641.         (Special characters converted to %XX form.)
  642.     content_type: str The MIME type for the data being sent. Defaults to
  643.         'application/atom+xml', this is only used if data is set.
  644.   """
  645.   deprecation('call to deprecated function HttpRequest')
  646.   full_uri = BuildUri(uri, url_params, escape_params)
  647.   (connection, full_uri) = PrepareConnection(service, full_uri)
  648.  
  649.   if extra_headers is None:
  650.     extra_headers = {}
  651.  
  652.   # Turn on debug mode if the debug member is set.
  653.   if service.debug:
  654.     connection.debuglevel = 1
  655.  
  656.   connection.putrequest(operation, full_uri)
  657.  
  658.   # If the list of headers does not include a Content-Length, attempt to 
  659.   # calculate it based on the data object.
  660.   if (data and not service.additional_headers.has_key('Content-Length') and 
  661.       not extra_headers.has_key('Content-Length')):
  662.     content_length = CalculateDataLength(data)
  663.     if content_length:
  664.       extra_headers['Content-Length'] = str(content_length)
  665.  
  666.   if content_type:
  667.     extra_headers['Content-Type'] = content_type 
  668.  
  669.   # Send the HTTP headers.
  670.   if isinstance(service.additional_headers, dict):
  671.     for header in service.additional_headers:
  672.       connection.putheader(header, service.additional_headers[header])
  673.   if isinstance(extra_headers, dict):
  674.     for header in extra_headers:
  675.       connection.putheader(header, extra_headers[header])
  676.   connection.endheaders()
  677.  
  678.   # If there is data, send it in the request.
  679.   if data:
  680.     if isinstance(data, list):
  681.       for data_part in data:
  682.         __SendDataPart(data_part, connection)
  683.     else:
  684.       __SendDataPart(data, connection)
  685.  
  686.   # Return the HTTP Response from the server.
  687.   return connection.getresponse()
  688.   
  689.  
  690. def __SendDataPart(data, connection):
  691.   """This method is deprecated, use atom.http._send_data_part"""
  692.   deprecated('call to deprecated function __SendDataPart')
  693.   if isinstance(data, str):
  694.     #TODO add handling for unicode.
  695.     connection.send(data)
  696.     return
  697.   elif ElementTree.iselement(data):
  698.     connection.send(ElementTree.tostring(data))
  699.     return
  700.   # Check to see if data is a file-like object that has a read method.
  701.   elif hasattr(data, 'read'):
  702.     # Read the file and send it a chunk at a time.
  703.     while 1:
  704.       binarydata = data.read(100000)
  705.       if binarydata == '': break
  706.       connection.send(binarydata)
  707.     return
  708.   else:
  709.     # The data object was not a file.
  710.     # Try to convert to a string and send the data.
  711.     connection.send(str(data))
  712.     return
  713.  
  714.  
  715. def CalculateDataLength(data):
  716.   """Attempts to determine the length of the data to send. 
  717.   
  718.   This method will respond with a length only if the data is a string or
  719.   and ElementTree element.
  720.  
  721.   Args:
  722.     data: object If this is not a string or ElementTree element this funtion
  723.         will return None.
  724.   """
  725.   if isinstance(data, str):
  726.     return len(data)
  727.   elif isinstance(data, list):
  728.     return None
  729.   elif ElementTree.iselement(data):
  730.     return len(ElementTree.tostring(data))
  731.   elif hasattr(data, 'read'):
  732.     # If this is a file-like object, don't try to guess the length.
  733.     return None
  734.   else:
  735.     return len(str(data))
  736.     
  737.  
  738. def deprecation(message):
  739.   warnings.warn(message, DeprecationWarning, stacklevel=2)
  740.